"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Skeleton } from "@/components/ui/skeleton"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import {
  ArrowLeft,
  TrendingUp,
  Activity,
  Target,
  RefreshCw,
  Trophy,
  AlertTriangle,
  Calendar,
  Filter,
  X,
  HelpCircle,
  Database,
  List
} from "lucide-react"
import { 
  getSignalAnalysis, 
  SignalAnalysisResult, 
  GetSignalAnalysisParams,
} from "@/lib/api/tracking"
import { useApiCall } from "@/lib/hooks/use-api-call"
import { useToast } from "@/hooks/use-toast"
import { cn } from "@/lib/utils"
import { ThemeSwitch } from "@/components/theme-switch"
import { UserNav } from "@/components/user-nav"

/**
 * 格式化百分比
 */
const formatPercent = (value: number, showSign = true, decimals = 2) => {
  const sign = showSign && value > 0 ? '+' : ''
  return `${sign}${value.toFixed(decimals)}%`
}

/**
 * 获取评级样式
 */
const getRatingStyle = (level: string) => {
  switch (level) {
    case 'S':
      return {
        bg: 'bg-purple-500/10 dark:bg-purple-500/20',
        text: 'text-purple-600 dark:text-purple-400',
        border: 'border-purple-500',
        label: 'S级'
      }
    case 'A':
      return {
        bg: 'bg-success/10 dark:bg-success/20',
        text: 'text-success',
        border: 'border-success',
        label: 'A级'
      }
    case 'B':
      return {
        bg: 'bg-blue-500/10 dark:bg-blue-500/20',
        text: 'text-blue-600 dark:text-blue-400',
        border: 'border-blue-500',
        label: 'B级'
      }
    case 'C':
      return {
        bg: 'bg-yellow-500/10 dark:bg-yellow-500/20',
        text: 'text-yellow-600 dark:text-yellow-500',
        border: 'border-yellow-500',
        label: 'C级'
      }
    case 'D':
      return {
        bg: 'bg-destructive/10 dark:bg-destructive/20',
        text: 'text-destructive',
        border: 'border-destructive',
        label: 'D级'
      }
    default:
      return {
        bg: 'bg-muted',
        text: 'text-muted-foreground',
        border: 'border-muted',
        label: level
      }
  }
}

/**
 * 统计卡片组件
 */
function StatCard({
  icon: Icon,
  title,
  value,
  description,
  trend
}: {
  icon: any
  title: string
  value: string | number
  description?: string
  trend?: 'up' | 'down' | 'neutral'
}) {
  const trendColor = trend === 'up' ? 'text-success' : trend === 'down' ? 'text-destructive' : 'text-muted-foreground'
  
  return (
    <Card className="transition-all duration-300 hover:shadow-lg hover:scale-105 cursor-default">
      <CardContent className="p-4">
        <div className="flex items-center justify-between mb-2">
          <p className="text-sm text-muted-foreground transition-colors duration-200">{title}</p>
          <Icon className={cn("w-4 h-4 transition-all duration-300", trendColor)} />
        </div>
        <p className="text-2xl font-bold font-mono transition-all duration-300">
          {value}
        </p>
        {description && (
          <p className="text-xs text-muted-foreground mt-1">{description}</p>
        )}
      </CardContent>
    </Card>
  )
}

/**
 * 信号详情卡片组件
 */
function SignalDetailCard({ 
  signal, 
  rank, 
  period,
  onViewTrades 
}: { 
  signal: SignalAnalysisResult
  rank: number
  period: number
  onViewTrades: (signalName: string) => void
}) {
  const ratingStyle = getRatingStyle(signal.ratingLevel)
  const isProfit = (signal.avgReturns[period] || 0) >= 0

  return (
    <Card className={cn("border-l-4 transition-all duration-300 hover:shadow-xl hover:-translate-y-1", ratingStyle.border)}>
      <CardContent className="p-4">
        {/* 标题行 */}
        <div className="flex items-start justify-between mb-3">
          <div className="flex items-center gap-3 flex-1">
            <Badge variant="outline" className="text-sm font-bold shrink-0">
              #{rank}
            </Badge>
            <div className="flex-1">
              <div className="flex items-center gap-2 flex-wrap">
                <h3 className="font-semibold text-base">{signal.signalName}</h3>
                <Badge className={cn("text-xs", ratingStyle.bg, ratingStyle.text)}>
                  {ratingStyle.label}
                </Badge>
              </div>
              <div className="flex items-center gap-2 mt-1 flex-wrap">
                <Badge variant="secondary" className="text-xs">
                  {signal.totalCount} 次交易
                </Badge>
                <Button
                  onClick={(e) => {
                    e.preventDefault()
                    e.stopPropagation()
                    console.log('🖱️ 按钮被点击, 信号:', signal.signalName)
                    onViewTrades(signal.signalName)
                  }}
                  variant="outline"
                  size="sm"
                  className="h-6 px-2 text-xs transition-all duration-200 hover:scale-105 active:scale-95 group"
                >
                  <List className="w-3 h-3 mr-1 transition-transform group-hover:scale-110" />
                  查看明细
                </Button>
              </div>
            </div>
          </div>

          {/* 评分 */}
          <div className="text-right shrink-0">
            <div className="flex items-center justify-end gap-1 mb-1">
              <p className="text-xs text-muted-foreground">综合评分</p>
              <TooltipProvider>
                <Tooltip delayDuration={200}>
                  <TooltipTrigger asChild>
                    <HelpCircle className="w-3 h-3 text-muted-foreground hover:text-accent cursor-help transition-colors" />
                  </TooltipTrigger>
                  <TooltipContent className="max-w-xs bg-popover text-popover-foreground border shadow-lg">
                    <p className="text-xs font-semibold mb-1">综合评分</p>
                    <p className="text-xs leading-relaxed">
                      基于胜率、收益率、夏普比率等多个指标综合计算得出的评分。
                    </p>
                    <div className="mt-2 space-y-0.5 text-xs">
                      <div><span className="font-medium text-purple-600 dark:text-purple-400">• 80-100分</span> S级（卓越）</div>
                      <div><span className="font-medium text-green-600 dark:text-green-400">• 70-80分</span> A级（优秀）</div>
                      <div><span className="font-medium text-blue-600 dark:text-blue-400">• 60-70分</span> B级（良好）</div>
                      <div><span className="font-medium text-yellow-700 dark:text-yellow-400">• 50-60分</span> C级（一般）</div>
                      <div><span className="font-medium text-red-600 dark:text-red-400">• &lt;50分</span> D级（较差）</div>
                    </div>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
            <p className={cn("text-2xl font-bold", ratingStyle.text)}>
              {signal.ratingScore.toFixed(1)}
            </p>
          </div>
        </div>

        {/* 核心指标网格 */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-3">
          {/* 胜率 */}
          <div>
            <div className="flex items-center gap-1 mb-1">
              <p className="text-xs text-muted-foreground">胜率</p>
              <TooltipProvider>
                <Tooltip delayDuration={200}>
                  <TooltipTrigger asChild>
                    <HelpCircle className="w-3 h-3 text-muted-foreground hover:text-accent cursor-help transition-colors" />
                  </TooltipTrigger>
                  <TooltipContent className="max-w-xs bg-popover text-popover-foreground border shadow-lg">
                    <p className="text-xs font-semibold mb-1">胜率 (Win Rate)</p>
                    <p className="text-xs leading-relaxed">
                      盈利交易占总交易次数的比例。胜率越高，该信号的可靠性越强。
                    </p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
            <p className={cn("text-lg font-bold", signal.winRate >= 70 ? "text-success" : "text-muted-foreground")}>
              {formatPercent(signal.winRate, false, 1)}
            </p>
            <p className="text-xs text-muted-foreground">
              {signal.winCount}胜/{signal.lossCount}负
            </p>
          </div>

          {/* T+N平均收益 */}
          <div>
            <div className="flex items-center gap-1 mb-1">
              <p className="text-xs text-muted-foreground">T+{period}收益</p>
              <TooltipProvider>
                <Tooltip delayDuration={200}>
                  <TooltipTrigger asChild>
                    <HelpCircle className="w-3 h-3 text-muted-foreground hover:text-accent cursor-help transition-colors" />
                  </TooltipTrigger>
                  <TooltipContent className="max-w-xs bg-popover text-popover-foreground border shadow-lg">
                    <p className="text-xs font-semibold mb-1">T+{period}平均收益</p>
                    <p className="text-xs leading-relaxed">
                      信号触发后第{period}个交易日的平均收益率。反映信号在该周期的盈利能力。
                    </p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
            <p className={cn(
              "text-lg font-bold font-mono",
              (signal.avgReturns[period] || 0) >= 0 ? "text-success" : "text-destructive"
            )}>
              {formatPercent(signal.avgReturns[period] || 0)}
            </p>
          </div>

          {/* 夏普比率 */}
          <div>
            <div className="flex items-center gap-1 mb-1">
              <p className="text-xs text-muted-foreground">夏普比率</p>
              <TooltipProvider>
                <Tooltip delayDuration={200}>
                  <TooltipTrigger asChild>
                    <HelpCircle className="w-3 h-3 text-muted-foreground hover:text-accent cursor-help transition-colors" />
                  </TooltipTrigger>
                  <TooltipContent className="max-w-xs bg-popover text-popover-foreground border shadow-lg">
                    <p className="text-xs font-semibold mb-1">夏普比率 (Sharpe Ratio)</p>
                    <p className="text-xs leading-relaxed mb-2">
                      衡量风险调整后收益的指标。数值越高，表示在承担相同风险下获得的收益越高。
                    </p>
                    <div className="space-y-0.5 text-xs">
                      <div><span className="font-medium text-green-600 dark:text-green-400">• &gt;1.0</span> 优秀</div>
                      <div><span className="font-medium text-blue-600 dark:text-blue-400">• 0.5-1.0</span> 良好</div>
                      <div><span className="font-medium text-gray-600 dark:text-gray-400">• &lt;0.5</span> 一般</div>
                    </div>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
            <p className="text-lg font-bold font-mono">
              {signal.sharpeRatio.toFixed(2)}
            </p>
          </div>

          {/* 平均持仓 */}
          <div>
            <div className="flex items-center gap-1 mb-1">
              <p className="text-xs text-muted-foreground">平均持仓</p>
              <TooltipProvider>
                <Tooltip delayDuration={200}>
                  <TooltipTrigger asChild>
                    <HelpCircle className="w-3 h-3 text-muted-foreground hover:text-accent cursor-help transition-colors" />
                  </TooltipTrigger>
                  <TooltipContent className="max-w-xs bg-popover text-popover-foreground border shadow-lg">
                    <p className="text-xs font-semibold mb-1">平均持仓天数</p>
                    <p className="text-xs leading-relaxed">
                      信号触发后平均持有股票的天数。持仓天数越短，资金周转效率越高。
                    </p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
            <p className="text-lg font-bold font-mono">
              {signal.avgHoldingDays.toFixed(1)}天
            </p>
          </div>
        </div>

        {/* 详细数据网格 */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3 pt-3 border-t">
          <div>
            <div className="flex items-center gap-1">
              <p className="text-xs text-muted-foreground">最大收益</p>
              <TooltipProvider>
                <Tooltip delayDuration={200}>
                  <TooltipTrigger asChild>
                    <HelpCircle className="w-3 h-3 text-muted-foreground hover:text-accent cursor-help transition-colors" />
                  </TooltipTrigger>
                  <TooltipContent className="max-w-xs bg-popover text-popover-foreground border shadow-lg">
                    <p className="text-xs font-semibold mb-1">最大收益</p>
                    <p className="text-xs leading-relaxed">
                      该信号历史上单次交易获得的最高收益率。反映信号的盈利上限。
                    </p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
            <p className="text-sm font-medium text-success font-mono">
              {formatPercent(signal.maxReturn)}
            </p>
          </div>
          <div>
            <div className="flex items-center gap-1">
              <p className="text-xs text-muted-foreground">最大亏损</p>
              <TooltipProvider>
                <Tooltip delayDuration={200}>
                  <TooltipTrigger asChild>
                    <HelpCircle className="w-3 h-3 text-muted-foreground hover:text-accent cursor-help transition-colors" />
                  </TooltipTrigger>
                  <TooltipContent className="max-w-xs bg-popover text-popover-foreground border shadow-lg">
                    <p className="text-xs font-semibold mb-1">最大亏损</p>
                    <p className="text-xs leading-relaxed">
                      该信号历史上单次交易出现的最大亏损率。反映信号的风险下限。
                    </p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
            <p className="text-sm font-medium text-destructive font-mono">
              {formatPercent(signal.maxLoss)}
            </p>
          </div>
          <div>
            <div className="flex items-center gap-1">
              <p className="text-xs text-muted-foreground">波动率</p>
              <TooltipProvider>
                <Tooltip delayDuration={200}>
                  <TooltipTrigger asChild>
                    <HelpCircle className="w-3 h-3 text-muted-foreground hover:text-accent cursor-help transition-colors" />
                  </TooltipTrigger>
                  <TooltipContent className="max-w-xs bg-popover text-popover-foreground border shadow-lg">
                    <p className="text-xs font-semibold mb-1">波动率 (Volatility)</p>
                    <p className="text-xs leading-relaxed">
                      衡量价格变动幅度的指标。数值越高，价格波动越剧烈，风险越大。
                    </p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
            <p className="text-sm font-medium font-mono">
              {signal.volatility.toFixed(2)}%
            </p>
          </div>
          <div>
            <div className="flex items-center gap-1">
              <p className="text-xs text-muted-foreground">所选周期</p>
              <TooltipProvider>
                <Tooltip delayDuration={200}>
                  <TooltipTrigger asChild>
                    <HelpCircle className="w-3 h-3 text-muted-foreground hover:text-accent cursor-help transition-colors" />
                  </TooltipTrigger>
                  <TooltipContent className="max-w-xs bg-popover text-popover-foreground border shadow-lg">
                    <p className="text-xs font-semibold mb-1">当前选择周期</p>
                    <p className="text-xs leading-relaxed">
                      当前筛选条件下选择的分析周期为 T+{period}。
                    </p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
            <p className="text-sm font-medium font-mono text-accent">
              T+{period}
            </p>
          </div>
        </div>
      </CardContent>
    </Card>
  )
}

/**
 * 信号分析页面
 */
export default function SignalAnalysisPage() {
  const router = useRouter()
  const { toast } = useToast()

  const [signals, setSignals] = useState<SignalAnalysisResult[]>([])
  const [sortBy, setSortBy] = useState<'rating' | 'winRate' | 'avgReturn' | 'count'>('rating')
  const [filterLevel, setFilterLevel] = useState<string>('all')
  const [startDate, setStartDate] = useState<string>('')
  const [endDate, setEndDate] = useState<string>('')
  const [period, setPeriod] = useState<number>(1)
  const [periodInput, setPeriodInput] = useState<string>('1') // 用于输入框的临时值

  // 获取信号分析数据
  const { execute: fetchAnalysis, isLoading } = useApiCall(
    (params?: GetSignalAnalysisParams) => getSignalAnalysis(params),
    {
      showToast: false,
      autoRetry: true,
    }
  )

  // 加载数据
  const loadData = async () => {
    try {
      console.log('🔍 开始加载信号分析数据...', { startDate, endDate, period })
      // 构建查询参数
      const params: GetSignalAnalysisParams = {}
      if (startDate) params.startDate = startDate
      if (endDate) params.endDate = endDate
      if (period) params.period = period
      
      // useApiCall 的 execute() 直接返回 data 部分，而不是完整的响应对象
      const data = await fetchAnalysis(params)
      console.log('📊 API返回数据:', data)
      
      if (data && Array.isArray(data)) {
        console.log('✅ 数据加载成功，信号数量:', data.length)
        setSignals(data)
        
        const dateRangeText = startDate && endDate 
          ? `（${startDate} 至 ${endDate}）` 
          : startDate 
            ? `（${startDate} 起）`
            : endDate
              ? `（截至 ${endDate}）`
              : ''
        
        const periodText = `T+${period}`
        
        toast({
          title: "数据加载成功",
          description: `共分析 ${data.length} 个交易信号${dateRangeText}，周期：${periodText}`,
          duration: 3000,
        })
      } else {
        console.warn('⚠️ API返回的数据结构异常:', data)
        toast({
          title: "数据格式异常",
          description: "返回的数据不是数组格式",
          variant: "destructive",
          duration: 5000,
        })
      }
    } catch (error) {
      console.error('❌ 加载信号分析数据失败:', error)
      toast({
        title: "数据加载失败",
        description: "无法获取信号分析数据，请检查网络连接",
        variant: "destructive",
        duration: 5000,
      })
    }
  }
  
  // 清除日期筛选并重新加载
  const clearDateFilter = async () => {
    setStartDate('')
    setEndDate('')
    // 清除后立即重新加载全部数据
    try {
      const data = await fetchAnalysis({})
      if (data && Array.isArray(data)) {
        setSignals(data)
        toast({
          title: "已清除筛选",
          description: `显示全部 ${data.length} 个交易信号`,
          duration: 3000,
        })
      }
    } catch (error) {
      console.error('清除筛选失败:', error)
    }
  }
  
  // 应用日期筛选
  const applyDateFilter = () => {
    loadData()
  }
  
  // 查看交易明细 - 跳转到新页面
  const handleViewTrades = (signalName: string) => {
    console.log('🔍 准备跳转到交易明细页, 信号名称:', signalName)
    
    // 构建查询参数
    const params = new URLSearchParams()
    params.append('signal', signalName)
    if (startDate) params.append('startDate', startDate)
    if (endDate) params.append('endDate', endDate)
    
    // 注意：由于配置了 trailingSlash: true，需要确保路径以 / 结尾
    const targetUrl = `/signals/trades/?${params.toString()}`
    console.log('🔗 目标URL:', targetUrl)
    
    // 跳转到交易明细页
    router.push(targetUrl)
  }

  // 初始加载和周期变化时加载数据
  useEffect(() => {
    loadData()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [period])

  // 计算统计数据
  const statistics = {
    totalSignals: signals.length,
    totalSamples: signals.reduce((sum, s) => sum + s.totalCount, 0), // 总样本数（所有交易次数）
    avgWinRate: signals.length > 0 
      ? signals.reduce((sum, s) => sum + s.winRate, 0) / signals.length 
      : 0,
    avgReturn: signals.length > 0
      ? signals.reduce((sum, s) => sum + (s.avgReturns[period] || 0), 0) / signals.length
      : 0,
    topRatedCount: signals.filter(s => s.ratingLevel === 'S' || s.ratingLevel === 'A').length,
  }

  // 排序和筛选
  const sortedAndFilteredSignals = signals
    .filter(signal => filterLevel === 'all' || signal.ratingLevel === filterLevel)
    .sort((a, b) => {
      switch (sortBy) {
        case 'rating':
          return b.ratingScore - a.ratingScore
        case 'winRate':
          return b.winRate - a.winRate
        case 'avgReturn':
          return (b.avgReturns[period] || 0) - (a.avgReturns[period] || 0)
        case 'count':
          return b.totalCount - a.totalCount
        default:
          return 0
      }
    })

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <header className="border-b bg-card">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Button
                variant="ghost"
                size="icon"
                onClick={() => router.back()}
              >
                <ArrowLeft className="w-5 h-5" />
              </Button>
              <div>
                <h1 className="text-2xl font-bold">信号有效性分析</h1>
                <p className="text-sm text-muted-foreground">
                  所有交易信号的统计分析与评级
                </p>
              </div>
            </div>

            <div className="flex items-center space-x-4">
              <Button
                onClick={loadData}
                disabled={isLoading}
                size="sm"
                className="bg-accent hover:bg-accent/90 transition-all duration-200 hover:scale-105 active:scale-95"
              >
                <RefreshCw className={cn("w-4 h-4 mr-2 transition-transform", isLoading && "animate-spin")} />
                刷新数据
              </Button>

              <div className="flex items-center space-x-2">
                <ThemeSwitch />
                <UserNav />
              </div>
            </div>
          </div>
        </div>
      </header>

      <main className="container mx-auto px-4 py-6">
        {isLoading && signals.length === 0 ? (
          // 加载骨架屏
          <div className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
              {Array.from({ length: 5 }).map((_, i) => (
                <Card key={i}>
                  <CardContent className="p-4">
                    <Skeleton className="h-4 w-20 mb-2" />
                    <Skeleton className="h-8 w-24 mb-2" />
                    <Skeleton className="h-3 w-16" />
                  </CardContent>
                </Card>
              ))}
            </div>
          </div>
        ) : (
          <div className="space-y-6">
            {/* 顶部统计卡片 */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
              <div className="animate-in fade-in slide-in-from-bottom-4 duration-500" style={{ animationDelay: '0ms', animationFillMode: 'both' }}>
                <StatCard
                  icon={Activity}
                  title="信号总数"
                  value={statistics.totalSignals}
                  description="已分析的交易信号"
                />
              </div>
              <div className="animate-in fade-in slide-in-from-bottom-4 duration-500" style={{ animationDelay: '100ms', animationFillMode: 'both' }}>
                <StatCard
                  icon={Database}
                  title="样本数量"
                  value={statistics.totalSamples.toLocaleString()}
                  description="所有信号的交易次数总和"
                />
              </div>
              <div className="animate-in fade-in slide-in-from-bottom-4 duration-500" style={{ animationDelay: '200ms', animationFillMode: 'both' }}>
                <StatCard
                  icon={Trophy}
                  title="高评级信号"
                  value={statistics.topRatedCount}
                  description="S级和A级信号数量"
                  trend="up"
                />
              </div>
              <div className="animate-in fade-in slide-in-from-bottom-4 duration-500" style={{ animationDelay: '300ms', animationFillMode: 'both' }}>
                <StatCard
                  icon={Target}
                  title="平均胜率"
                  value={formatPercent(statistics.avgWinRate, false, 1)}
                  description="所有信号的平均胜率"
                  trend={statistics.avgWinRate >= 70 ? 'up' : 'neutral'}
                />
              </div>
              <div className="animate-in fade-in slide-in-from-bottom-4 duration-500" style={{ animationDelay: '400ms', animationFillMode: 'both' }}>
                <StatCard
                  icon={TrendingUp}
                  title={`平均T+${period}收益`}
                  value={formatPercent(statistics.avgReturn)}
                  description="所有信号在该周期的平均收益"
                  trend={statistics.avgReturn >= 0 ? 'up' : 'down'}
                />
              </div>
            </div>

            {/* 筛选条件 */}
            <Card className="animate-in fade-in slide-in-from-bottom-3 duration-500" style={{ animationDelay: '500ms', animationFillMode: 'both' }}>
              <CardContent className="p-4">
                <div className="flex flex-col space-y-4">
                  <div className="flex items-center gap-2">
                    <Filter className="w-4 h-4 text-muted-foreground" />
                    <span className="text-sm font-medium">筛选条件</span>
                  </div>

                  <div className="flex flex-col md:flex-row items-start md:items-end gap-4">
                    {/* 开始日期 */}
                    <div className="flex-1 w-full md:w-auto">
                      <Label htmlFor="start-date" className="text-xs text-muted-foreground mb-1">
                        开始日期
                      </Label>
                      <Input
                        id="start-date"
                        type="date"
                        value={startDate}
                        onChange={(e) => setStartDate(e.target.value)}
                        className="w-full"
                        placeholder="选择开始日期"
                      />
                    </div>

                    {/* 结束日期 */}
                    <div className="flex-1 w-full md:w-auto">
                      <Label htmlFor="end-date" className="text-xs text-muted-foreground mb-1">
                        结束日期
                      </Label>
                      <Input
                        id="end-date"
                        type="date"
                        value={endDate}
                        onChange={(e) => setEndDate(e.target.value)}
                        className="w-full"
                        placeholder="选择结束日期"
                      />
                    </div>

                    {/* 分析周期选择 */}
                    <div className="w-full md:w-auto">
                      <div className="flex items-center gap-1 mb-1">
                        <Label htmlFor="period" className="text-xs text-muted-foreground">
                          分析周期 (天数)
                        </Label>
                        <TooltipProvider>
                          <Tooltip delayDuration={200}>
                            <TooltipTrigger asChild>
                              <HelpCircle className="w-3 h-3 text-muted-foreground hover:text-accent cursor-help transition-colors" />
                            </TooltipTrigger>
                            <TooltipContent className="max-w-xs bg-popover text-popover-foreground border shadow-lg">
                              <p className="text-xs font-semibold mb-1">分析周期天数</p>
                              <p className="text-xs leading-relaxed mb-2">
                                自定义持仓天数来分析信号表现，支持1-30天。
                              </p>
                              <div className="space-y-1 text-xs">
                                <div><span className="font-medium text-green-600 dark:text-green-400">• 1-3天</span> 短线交易</div>
                                <div><span className="font-medium text-blue-600 dark:text-blue-400">• 4-10天</span> 中线持有</div>
                                <div><span className="font-medium text-purple-600 dark:text-purple-400">• 11-30天</span> 长线投资</div>
                              </div>
                            </TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </div>
                      <div className="flex items-center gap-2">
                        <Input
                          id="period"
                          type="number"
                          min="1"
                          max="30"
                          value={periodInput}
                          onChange={(e) => {
                            const inputValue = e.target.value
                            setPeriodInput(inputValue) // 允许任何输入，包括空值
                            
                            // 如果是有效数字，实时更新 period
                            if (inputValue !== '') {
                              const value = parseInt(inputValue)
                              if (!isNaN(value) && value >= 1 && value <= 30) {
                                setPeriod(value)
                              }
                            }
                          }}
                          onBlur={(e) => {
                            // 失去焦点时确保有有效值
                            const inputValue = e.target.value
                            if (inputValue === '') {
                              setPeriod(1)
                              setPeriodInput('1')
                              return
                            }
                            const value = parseInt(inputValue)
                            if (isNaN(value) || value < 1) {
                              setPeriod(1)
                              setPeriodInput('1')
                            } else if (value > 30) {
                              setPeriod(30)
                              setPeriodInput('30')
                            } else {
                              setPeriod(value)
                              setPeriodInput(value.toString())
                            }
                          }}
                          className="w-20 text-center font-mono"
                          placeholder="天"
                        />
                        <div className="flex gap-1">
                          <Button
                            type="button"
                            variant={period === 1 ? "default" : "outline"}
                            size="sm"
                            className="h-8 px-2 text-xs transition-all duration-200 hover:scale-110 active:scale-95"
                            onClick={() => {
                              setPeriod(1)
                              setPeriodInput('1')
                            }}
                          >
                            T+1
                          </Button>
                          <Button
                            type="button"
                            variant={period === 3 ? "default" : "outline"}
                            size="sm"
                            className="h-8 px-2 text-xs transition-all duration-200 hover:scale-110 active:scale-95"
                            onClick={() => {
                              setPeriod(3)
                              setPeriodInput('3')
                            }}
                          >
                            T+3
                          </Button>
                          <Button
                            type="button"
                            variant={period === 5 ? "default" : "outline"}
                            size="sm"
                            className="h-8 px-2 text-xs transition-all duration-200 hover:scale-110 active:scale-95"
                            onClick={() => {
                              setPeriod(5)
                              setPeriodInput('5')
                            }}
                          >
                            T+5
                          </Button>
                          <Button
                            type="button"
                            variant={period === 10 ? "default" : "outline"}
                            size="sm"
                            className="h-8 px-2 text-xs transition-all duration-200 hover:scale-110 active:scale-95"
                            onClick={() => {
                              setPeriod(10)
                              setPeriodInput('10')
                            }}
                          >
                            T+10
                          </Button>
                        </div>
                      </div>
                    </div>

                    {/* 操作按钮 */}
                    <div className="flex gap-2">
                      <Button
                        onClick={applyDateFilter}
                        disabled={isLoading}
                        size="sm"
                        className="bg-accent hover:bg-accent/90 transition-all duration-200 hover:scale-105 active:scale-95"
                      >
                        <Filter className="w-4 h-4 mr-2" />
                        应用筛选
                      </Button>

                      {(startDate || endDate) && (
                        <Button
                          onClick={clearDateFilter}
                          variant="outline"
                          size="sm"
                          className="transition-all duration-200 hover:scale-105 active:scale-95 animate-in fade-in slide-in-from-right duration-300"
                        >
                          <X className="w-4 h-4 mr-2" />
                          清除
                        </Button>
                      )}
                    </div>
                  </div>

                  {/* 筛选条件提示 */}
                  {(startDate || endDate || period !== 1) && (
                    <div className="flex items-center gap-2 text-xs flex-wrap">
                      {(startDate || endDate) && (
                        <Badge variant="secondary" className="text-xs">
                          <Calendar className="w-3 h-3 mr-1" />
                          {startDate && endDate 
                            ? `${startDate} 至 ${endDate}` 
                            : startDate 
                              ? `${startDate} 起`
                              : `截至 ${endDate}`
                          }
                        </Badge>
                      )}
                      {period !== 1 && (
                        <Badge variant="secondary" className="text-xs">
                          <Activity className="w-3 h-3 mr-1" />
                          周期: T+{period}
                        </Badge>
                      )}
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>

            {/* 筛选和排序控制 */}
            <Card className="animate-in fade-in slide-in-from-bottom-3 duration-500" style={{ animationDelay: '600ms', animationFillMode: 'both' }}>
              <CardContent className="p-4">
                <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
                  <div className="flex items-center gap-2">
                    <Filter className="w-4 h-4 text-muted-foreground" />
                    <span className="text-sm font-medium">筛选与排序</span>
                  </div>

                  <div className="flex flex-wrap items-center gap-3">
                    {/* 评级筛选 */}
                    <Select value={filterLevel} onValueChange={setFilterLevel}>
                      <SelectTrigger className="w-[140px]">
                        <SelectValue placeholder="评级筛选" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">全部评级</SelectItem>
                        <SelectItem value="S">S级信号</SelectItem>
                        <SelectItem value="A">A级信号</SelectItem>
                        <SelectItem value="B">B级信号</SelectItem>
                        <SelectItem value="C">C级信号</SelectItem>
                        <SelectItem value="D">D级信号</SelectItem>
                      </SelectContent>
                    </Select>

                    {/* 排序方式 */}
                    <Select value={sortBy} onValueChange={(value: any) => setSortBy(value)}>
                      <SelectTrigger className="w-[140px]">
                        <SelectValue placeholder="排序方式" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="rating">综合评分</SelectItem>
                        <SelectItem value="winRate">胜率排序</SelectItem>
                        <SelectItem value="avgReturn">收益排序</SelectItem>
                        <SelectItem value="count">交易次数</SelectItem>
                      </SelectContent>
                    </Select>

                    {/* 结果统计 */}
                    <Badge variant="outline" className="text-sm">
                      显示 {sortedAndFilteredSignals.length} / {signals.length} 个信号
                    </Badge>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 评级说明 */}
            <Card className="bg-accent/5 animate-in fade-in slide-in-from-bottom-3 duration-500" style={{ animationDelay: '700ms', animationFillMode: 'both' }}>
              <CardContent className="p-4">
                <div className="flex flex-wrap items-center justify-center gap-6 text-xs">
                  <div className="flex items-center gap-2">
                    <Badge className="bg-purple-500/20 text-purple-600 dark:text-purple-400 border-purple-500">S</Badge>
                    <span className="text-muted-foreground">卓越 (80-100分)</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge className="bg-success/20 text-success border-success">A</Badge>
                    <span className="text-muted-foreground">优秀 (70-80分)</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge className="bg-blue-500/20 text-blue-600 dark:text-blue-400 border-blue-500">B</Badge>
                    <span className="text-muted-foreground">良好 (60-70分)</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge className="bg-yellow-500/20 text-yellow-600 dark:text-yellow-500 border-yellow-500">C</Badge>
                    <span className="text-muted-foreground">一般 (50-60分)</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge className="bg-destructive/20 text-destructive border-destructive">D</Badge>
                    <span className="text-muted-foreground">较差 (&lt;50分)</span>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 信号卡片列表 */}
            <div>
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-xl font-semibold">信号详细分析</h2>
              </div>

              <div className="space-y-3">
                {sortedAndFilteredSignals.map((signal, index) => (
                  <div
                    key={signal.signalName}
                    className="animate-in fade-in slide-in-from-bottom-2"
                    style={{
                      animationDelay: `${800 + index * 50}ms`,
                      animationDuration: '400ms',
                      animationFillMode: 'both',
                    }}
                  >
                    <SignalDetailCard 
                      signal={signal} 
                      rank={index + 1}
                      period={period}
                      onViewTrades={handleViewTrades}
                    />
                  </div>
                ))}
              </div>

              {sortedAndFilteredSignals.length === 0 && (
                <Card>
                  <CardContent className="flex flex-col items-center justify-center py-12">
                    <AlertTriangle className="w-12 h-12 text-muted-foreground mb-4" />
                    <p className="text-lg font-semibold mb-2">暂无符合条件的信号</p>
                    <p className="text-sm text-muted-foreground">
                      尝试调整筛选条件
                    </p>
                  </CardContent>
                </Card>
              )}
            </div>
          </div>
        )}
      </main>
    </div>
  )
}


